package history

import (
	"strconv"
	"strings"
)

/**
 * @description: 飞协博
 * @keyword:
 * @author: kami
 * @date 2024/3/12 10:20
 */
func validIpAddress(ip string) bool {
	var ipArray = strings.Split(ip, ".")
	for i := 0; i < len(ipArray); i++ {
		var ipNum, _ = strconv.Atoi(ipArray[i])
		if ipNum < 0 || ipNum > 255 {
			return false
		}
	}
	return true
}

func restoreIpAddresses(s string) []string {
	var res []string
	var trackBack func(s string, curIdx int, curRes []string)
	trackBack = func(s string, curIdx int, curRes []string) {
		if len(curRes) == 4 && curIdx == len(s) {
			res = append(res, curRes[0]+"."+curRes[1]+"."+curRes[2]+"."+curRes[3])
			return
		}
		if len(curRes) != 4 && curIdx == len(s) {
			return
		}
		for i := 1; i <= 3; i++ {
			if curIdx+i > len(s) {
				return
			}
			if validIpNum(s[curIdx : curIdx+i]) {
				curRes = append(curRes, s[curIdx:curIdx+i])
				trackBack(s, curIdx+i, curRes)
				curRes = curRes[:len(curRes)-1]
			}
		}
	}
	trackBack(s, 0, []string{})
	return res
}

func validIpNum(s string) bool {
	if len(s) > 3 || len(s) == 0 {
		return false
	}
	if s[0] == '0' && len(s) > 1 {
		return false
	}
	if len(s) == 3 {
		if s[0] == '1' {
			return true
		}
		if s[0] == '2' && s[1] >= '0' && s[1] <= '4' {
			return true
		}
		if s[0] == '2' && s[1] == '5' && s[2] <= '5' {
			return true
		}
		return false
	}
	return true
}
